# -*- coding: utf-8 -*-

class PurchaseOrderController < ApplicationController
  before_filter :employee_authorize, :except => [:login, :index, :index1, :index2]
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter, :except => [:productNeedPurchase, :productNeedEntry, :getSaleOrdersOfPurchaseById, :hxListForPurchase, :getEntryProductQuantityForPurchase, :purchase_order_print_header, :purchase_order_print_content, :purchase_order_print_footer, :purchasesReport, :getPurchasesForReport, :productStockRemindReport, :getProductStockRemindForReport]
  after_filter :sys_after_log

  #显示可以添加采购订单的页面。
  def newPurchaseOrder
    #准备一下默认的收货地址
    @purchasingShippingAddress = SysParam.find(session[:company_id]).purchasing_shipping_address
    #判断一下，是不是以销定采
    @purchaseBaseOnSales = SysParam.find(session[:company_id]).purchase_base_on_sales
  end

  def editPurchaseOrder

  end

  #空方法，为权限所用
  def purchaseOrderList

  end

  #采购审批页面
  def purchaseOrderAuditList

  end

  #为权限设置
  def entryForPurchaseList

  end

  #订单审批--  一般由会计部审批
  def auditPurchaseOrder

  end

  #可入库采购订单
  def purchaseOrderForWarehousingList

  end

  #显示审批撤消的介面。
  def auditPurchaseOrderForCancel

  end

  #显示销售转采购的页面
  def newPurchaseFromSale

  end

  #显示采购订单的付款记录页面
  def payablesListForPurchase

  end

  #分析决定
  def analysis

  end

  def getAllPurchaseOrders
    begin
      conditionsHash = Hash.new
      paramsHash = Hash.new
      paramsHash[:offset] = params[:start].to_i
      paramsHash[:limit] = params[:limit].to_i
      conditionsStr = ''

      if params[:purchase_order_number].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'seq_number = :purchase_order_number'
        else
          conditionsStr = conditionsStr+' AND seq_number = :purchase_order_number'
        end
        conditionsHash[:purchase_order_number] = params[:purchase_order_number].to_i
      end

      if params[:sale_order_number].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'sale_orders.seq_number = :sale_order_number'
        else
          conditionsStr = conditionsStr+' AND sale_orders.seq_number = :sale_order_number'
        end
        conditionsHash[:sale_order_number] = params[:sale_order_number].to_i
      end

      if params[:auditing_status].to_s != '' && params[:auditing_status] != ' '
        if conditionsStr == ''
          conditionsStr = 'auditing_status like :auditing_status'
        else
          conditionsStr = conditionsStr+' AND auditing_status like :auditing_status'
        end
        conditionsHash[:auditing_status] = '%'+params[:auditing_status].to_s+'%'
      elsif params[:auditing_status] == ' '
        if conditionsStr == ''
          conditionsStr = 'auditing_status = :auditing_status'
        else
          conditionsStr = conditionsStr+' AND auditing_status = :auditing_status'
        end
        conditionsHash[:auditing_status] = ''
      end

      if params[:vendor_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'vendor_id = :vendor_id'
        else
          conditionsStr = conditionsStr+' AND vendor_id = :vendor_id'
        end
        conditionsHash[:vendor_id] = params[:vendor_id].to_i
      end

      if params[:employee_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'employee_id = :employee_id'
        else
          conditionsStr = conditionsStr+' AND employee_id = :employee_id'
        end
        conditionsHash[:employee_id] = params[:employee_id].to_i
      end

      #显示产品
      if params[:product_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'purchase_order_details.product_id = :product_id'
        else
          conditionsStr = conditionsStr+' AND purchase_order_details.product_id = :product_id'
        end
        conditionsHash[:product_id] = params[:product_id].to_i
      end

      if params[:begin_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date >= :begin_date'
        else
          conditionsStr = conditionsStr+' AND action_date >= :begin_date'
        end
        conditionsHash[:begin_date] = params[:begin_date].to_date
      end

      if params[:end_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date <= :end_date'
        else
          conditionsStr = conditionsStr+' AND action_date <= :end_date'
        end
        conditionsHash[:end_date] = params[:end_date].to_date
      end

      if params[:c_begin_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'purchase_orders.created_at >= :created_at_begin'
        else
          conditionsStr = conditionsStr+' AND purchase_orders.created_at >= :created_at_begin'
        end
        conditionsHash[:created_at_begin] = params[:c_begin_date].to_date.to_s + ' 00:00:00'
      end

      if params[:c_end_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'purchase_orders.created_at <= :created_at_end'
        else
          conditionsStr = conditionsStr+' AND purchase_orders.created_at <= :created_at_end'
        end
        conditionsHash[:created_at_end] = params[:c_end_date].to_date.to_s + ' 59:59:59'
      end

      role = Role.find(session[:role_id])
      if role.cross_company == "否"
        if conditionsStr == ''
          conditionsStr = 'purchase_orders.company_id = :company_id'
        else
          conditionsStr = conditionsStr+' AND purchase_orders.company_id = :company_id'
        end
        conditionsHash[:company_id] = session[:company_id]
      end

      count = PurchaseOrder.countAllPurchaseOrders conditionsStr, conditionsHash
      purchaseOrders = PurchaseOrder.findAllPurchaseOrders conditionsStr, conditionsHash, paramsHash

      #jsonStr="{totalProperty:"+count.to_s+",root:"+purchaseOrders.to_json(:include=>[:employee,:department,:vendor,:auditor,:warehouse_employee])+"}"
      if session[:financial_management] == "是"
        jsonStr="{totalProperty:"+count.to_s+",root:"+purchaseOrders.to_json(:include => {:company => {:only => [:id, :name]}, :employee => {:only => [:id, :name]}, :department => {:only => [:id, :name]}, :vendor => {:only => [:id, :name]}, :auditor => {:only => [:id, :name]}, :warehouse_employee => {:only => [:id, :name]}})+"}"

      else
        jsonStr="{totalProperty:"+count.to_s+",root:"+purchaseOrders.to_json(:except => [:amount, :tax_amount, :value_added_tax], :include => {:company => {:only => [:id, :name]}, :employee => {:only => [:id, :name]}, :department => {:only => [:id, :name]}, :vendor => {:only => [:id, :name]}, :auditor => {:only => [:id, :name]}, :warehouse_employee => {:only => [:id, :name]}})+"}"

      end

      #logger.info jsonStr
      render :text => jsonStr, :layout => false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip, e.to_s)
    end
  end

  #得到某一个采购订单的信息
  def getPurchaseOrderById
    purchaseOrder = PurchaseOrder.where(id:params[:id]).includes([:vendor]).first
    rootStr = purchaseOrder.to_json(:include => {:vendor => {:only => [:id, :name]}})
    jsonStr = "{root:["+rootStr+"]}"
    render :text => jsonStr, :layout => false
  end

  #得到某一个采购订单的详细信息
  def getPurchaseOrderDetailsById
    begin
      purchaseOrderDetails = PurchaseOrderDetail.where(purchase_order_id:params[:purchase_order_id]).includes([:product, :sale_order])
      jsonStr="{totalProperty:"+purchaseOrderDetails.length.to_s+",root:"+purchaseOrderDetails.to_json(:include => [:product, :sale_order])+"}"
      #logger.info jsonStr
      render :text => jsonStr, :layout => false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip, e.to_s)
    end
  end

  #在编辑时,得到某一个采购订单的详细信息
  def getPurchaseOrderDetailsByIdForEdit
    begin
      #得到这张采购订单的详细表中听所有ProductId
      purchaseOrder = PurchaseOrder.find(params[:purchase_order_id])
      saleOrderIdArray = Array.new
      productIdArray = Array.new
      purchaseOrder.purchase_order_details.each do |purchaseOrderDetail|
        saleOrderIdArray << purchaseOrderDetail.sale_order_id
        productIdArray << purchaseOrderDetail.product_id
      end
      #这里要考虑到无销售订单的情况，所以无销售订单的balance_quantity要处理成一个比较大的数字。
      purchaseOrderDetails = PurchaseOrderDetail.all(:select => "pd.id,pd.purchase_order_id,pd.sale_order_id,pd.unit_price,pd.tax_price,pd.quantity,pd.amount,pd.tax_amount,pd.value_added_tax,pd.description,p.id as product_id,p.is_suit,p.name as product_name,p.number,p.unit,p.spec,so.order_number as sale_order_number,case when ifnull(sd.quantity,0) = 0 THEN 10000 - newpd.quantity + pd.quantity ELSE ifnull(sd.quantity,0)- newpd.quantity + pd.quantity END as balance_quantity,ed.quantity as ed_quantity,ifnull(pc1.stock_quantity,0) as stock_quantity_1,ifnull(pc2.stock_quantity,0) as stock_quantity_2", :joins => " pd
      left join (select product_id,sum(quantity) quantity from purchase_order_details pd where pd.sale_order_id in (#{saleOrderIdArray.join(",")}) AND pd.product_id in (#{productIdArray.join(",")}) group by sale_order_id,product_id) newpd on newpd.product_id = pd.product_id
      left join sale_order_details sd on sd.sale_order_id = pd.sale_order_id AND sd.product_id = pd.product_id
      left join products p on p.id = pd.product_id
      left join sale_orders so on so.id = pd.sale_order_id
      left join (select sum(ed.quantity) as quantity,ed.sale_order_id,ed.product_id from warehousing_entries we left join warehousing_entry_details ed on we.id = ed.warehousing_entry_id
                 where we.purchase_order_id = #{purchaseOrder.id} group by ed.sale_order_id,ed.product_id
                ) ed on pd.sale_order_id = ed.sale_order_id and pd.product_id = ed.product_id
      left join (select product_id,sum(quantity) as stock_quantity from product_collections where is_locked = 0 AND product_id in (#{productIdArray.join(",")}) AND warehouse_id =1 group by product_id) pc1 on pc1.product_id = p.id
      left join (select product_id,sum(quantity) as stock_quantity from product_collections where is_locked = 0 AND product_id in (#{productIdArray.join(",")}) AND warehouse_id =2 group by product_id) pc2 on pc2.product_id = p.id
      where pd.purchase_order_id = #{purchaseOrder.id}
      ", :include => [:product, :sale_order])
      jsonStr="{totalProperty:"+purchaseOrderDetails.length.to_s+",root:"+purchaseOrderDetails.to_json(:include => [:product, :sale_order])+"}"
      #logger.info jsonStr
      render :text => jsonStr, :layout => false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip, e.to_s)
    end
  end

  #为采购订单的审批准备的一个功能
  def getAllPurchaseOrdersByAuditStatus
    conditionsHash = Hash.new
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i
    conditionsStr = ''

    if params[:order_number].to_s != ''
      conditionsStr = 'seq_number in (:order_number)'
      conditionsHash[:order_number] = params[:order_number].split(/,/)
    end

    if params[:auditing_status].to_s != '' && params[:auditing_status].to_s != ' '
      if conditionsStr == ''
        conditionsStr = "auditing_status like :auditing_status"
      else
        conditionsStr = conditionsStr+' AND auditing_status like :auditing_status'
      end
      conditionsHash[:auditing_status] = '%'+params[:auditing_status].to_s+'%'
      #如果没有选择特定的审批状态，默认情况下，只显示“申请”的
    elsif params[:auditing_status].to_s == ' '
      if conditionsStr == ''
        conditionsStr = "auditing_status like :auditing_status"
      else
        conditionsStr = conditionsStr+' AND auditing_status like :auditing_status'
      end
      conditionsHash[:auditing_status] = "%#{Constants::APPLY}%"
    else
      if conditionsStr == ''
        conditionsStr = "auditing_status like :auditing_status"
      else
        conditionsStr = conditionsStr+' AND auditing_status like :auditing_status'
      end
      conditionsHash[:auditing_status] = "%#{Constants::APPLY}%"
    end

    if params[:vendor_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'vendor_id = :vendor_id'
      else
        conditionsStr = conditionsStr+' AND vendor_id = :vendor_id'
      end
      conditionsHash[:vendor_id] = params[:vendor_id].to_i
    end

    if params[:begin_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'action_date >= :begin_date'
      else
        conditionsStr = conditionsStr+' AND action_date >= :begin_date'
      end
      conditionsHash[:begin_date] = params[:begin_date].to_date
    end

    if params[:end_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = 'action_date <= :end_date'
      else
        conditionsStr = conditionsStr+' AND action_date <= :end_date'
      end
      conditionsHash[:end_date] = params[:end_date].to_date
    end

    count = PurchaseOrder.countAllPurchaseOrders conditionsStr, conditionsHash
    purchaseOrders = PurchaseOrder.findAllPurchaseOrders conditionsStr, conditionsHash, paramsHash
    #jsonStr="{totalProperty:"+count.to_s+",root:"+purchaseOrders.to_json(:include=>[:employee,:department,:vendor,:auditor,:warehouse_employee])+"}"
    jsonStr="{totalProperty:"+count.to_s+",root:"+purchaseOrders.to_json(:include => {:employee => {:only => [:id, :name]}, :department => {:only => [:id, :name]}, :vendor => {:only => [:id, :name]}, :auditor => {:only => [:id, :name]}, :warehouse_employee => {:only => [:id, :name]}})+"}"
    #logger.info jsonStr
    render :text => jsonStr, :layout => false
  end

  #查询采购订单，合呼要求的，可以转化为入库单。
  def getAllPurchaseOrdersForWarehousingEntry
    begin
      conditionsHash = Hash.new
      paramsHash = Hash.new
      paramsHash[:offset] = params[:start].to_i
      paramsHash[:limit] = params[:limit].to_i

      conditionsStr = '(auditing_status like :auditing_status1 AND auditing_status not like :auditing_status2) '
      #在这儿补充一些可以入库的必要条件，比如不能是已经撤消的或申请撤消的。也不能是暂存的。
      conditionsHash[:auditing_status1] = "%通过%"
      conditionsHash[:auditing_status2] = "%撤消%"

      if params[:order_number].to_s != ''
        conditionsStr = conditionsStr+' AND seq_number in (:order_number)'
        conditionsHash[:order_number] = params[:order_number].split(/,/)
      end

      if params[:vendor_id].to_s != ''
        conditionsStr = conditionsStr+' AND vendor_id = :vendor_id'
        conditionsHash[:vendor_id] = params[:vendor_id].to_i
      end

      if params[:begin_date].to_s != ''
        conditionsStr = conditionsStr+' AND action_date >= :begin_date'
        conditionsHash[:begin_date] = params[:begin_date].to_date
      end

      if params[:end_date].to_s != ''
        conditionsStr = conditionsStr+' AND action_date <= :end_date'
        conditionsHash[:end_date] = params[:end_date].to_date
      end

      role = Role.find(session[:role_id])
      if role.cross_company == "否"
        if conditionsStr == ''
          conditionsStr = 'company_id = :company_id'
        else
          conditionsStr = conditionsStr+' AND company_id = :company_id'
        end
        conditionsHash[:company_id] = session[:company_id]
      end

      count = PurchaseOrder.countAllPurchaseOrders conditionsStr, conditionsHash
      purchaseOrders = PurchaseOrder.findAllPurchaseOrders conditionsStr, conditionsHash, paramsHash

      #jsonStr="{totalProperty:"+count.to_s+",root:"+purchaseOrders.to_json(:include=>[:employee,:department,:vendor,:auditor,:warehouse_employee])+"}"
      if session[:financial_management] == "是"
        jsonStr="{totalProperty:"+count.to_s+",root:"+purchaseOrders.to_json(:include => {:company => {:only => [:id, :name]}, :employee => {:only => [:id, :name]}, :department => {:only => [:id, :name]}, :vendor => {:only => [:id, :name]}, :auditor => {:only => [:id, :name]}, :warehouse_employee => {:only => [:id, :name]}})+"}"
      else

        jsonStr="{totalProperty:"+count.to_s+",root:"+purchaseOrders.to_json(:except => [:amount], :include => {:company => {:only => [:id, :name]}, :employee => {:only => [:id, :name]}, :department => {:only => [:id, :name]}, :vendor => {:only => [:id, :name]}, :auditor => {:only => [:id, :name]}, :warehouse_employee => {:only => [:id, :name]}})+"}"
        logger.info jsonStr
      end
      #logger.info jsonStr
      render :text => jsonStr, :layout => false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip, e.to_s)
    end
  end

  #更新审批状态
  #当前，2011-07-20对于，采购的审批，主要是针对新增的，对于修改，是没有限制的。不需要审批。
  def updateAuditingStatus
    purchaseOrder = PurchaseOrder.find(params[:purchase_order_id])
    info = nil
    if purchaseOrder != nil
      PurchaseOrder.transaction do
        auditingStatus = params[:auditing_status]
        if (auditingStatus == "是")
          auditingStatus = Constants::PASS_APPLY_ADD
        else
          auditingStatus = Constants::REJECT_APPLY_ADD
        end
        purchaseOrder.auditing_status = auditingStatus
        purchaseOrder.auditor_id = session[:employee_id]
        purchaseOrder.audit_opinion = params[:audit_opinion]
        purchaseOrder.save!

        #在这儿对比一下采购修改后，与入库发生的变化，以从新设置采购订单的入库状态。
        diffs = PurchaseOrder.diff_purchase_entry(purchaseOrder.id)
        #不等于0有二种情况，一是采购的多了入库的少了，二是入的多采购的少了。不管如何，入库状态都设置为""
        if diffs.length !=0
          purchaseOrder.store_status = Constants::ENTERING
        elsif diffs.length == 0
          purchaseOrder.store_status = Constants::FINISH_ENTRY
        end
        purchaseOrder.save!
      end
      info = "成功"
    else
      info = "失败"
    end
    result = "{success:true,info:'#{info}'}"
    render :text => result, :layout => false
  end

  #创建新的采购订单
  def create
    paramsHash = Util.paramsPreprocessToHash(params[:data])
    #productHash = paramsHash["products"][0]

    purchaseOrder = PurchaseOrder.new
    purchaseOrder.company_id = paramsHash['company_id']
    purchaseOrder.department_id = session[:department_id]
    purchaseOrder.employee_id = session[:employee_id]
    purchaseOrder.vendor_id = paramsHash['vendor_id']
    purchaseOrder.linkman = paramsHash['linkman']
    purchaseOrder.phone = paramsHash['phone']
    purchaseOrder.delivery_address = paramsHash['delivery_address']
    purchaseOrder.contract_number = paramsHash['contract_number']
    purchaseOrder.tax_rate = paramsHash['tax_rate']
    purchaseOrder.action_date = paramsHash['action_date']
    purchaseOrder.description = paramsHash['description']

    #判断一下当前用户角色是否需求审批
    sysParam = SysParam.find_by_company_id(session[:company_id])

    #判断是暂存还是提交,结合审批一起处理，如果是暂存，就不处理审批的情形
    if paramsHash['temporary'] == '1'
      purchaseOrder.deal_with_status = Constants::TEMP_ADD
    else
      if sysParam.audit_for_purchase_add == "否"
        purchaseOrder.auditing_status = Constants::PASS_APPLY_ADD
        purchaseOrder.deal_with_status = ''
      else
        purchaseOrder.auditing_status = Constants::AUDIT_APPLY_ADD
      end
    end

    #插入products信息
    productsHashArray = paramsHash["products"]
    productsHashArray.each do |productHash|
      #只有当用户选择的产品不为空时，才有详细订单。
      if productHash["product_id"] !=""
        purchaseOrderDetail = PurchaseOrderDetail.new
        purchaseOrderDetail.sale_order_id = productHash["sale_order_id"]
        purchaseOrderDetail.product_id = productHash["product_id"]
        purchaseOrderDetail.quantity = productHash["quantity"]
        purchaseOrderDetail.unit_price = productHash["unit_price"]
        purchaseOrderDetail.amount = productHash["amount"]
        purchaseOrderDetail.tax_price = productHash["tax_price"]
        purchaseOrderDetail.tax_amount = productHash["tax_amount"]
        purchaseOrderDetail.value_added_tax = productHash["value_added_tax"]
        purchaseOrder.amount = purchaseOrder.amount + purchaseOrderDetail.amount #计算订单总金额
        purchaseOrder.tax_amount = purchaseOrder.tax_amount + purchaseOrderDetail.tax_amount #计算订单总金额(含税)
        purchaseOrder.value_added_tax = purchaseOrder.value_added_tax + purchaseOrderDetail.value_added_tax #计算订单总金额(含税)
        purchaseOrderDetail.description = productHash["description"]
        purchaseOrder.purchase_order_details << purchaseOrderDetail
      end
    end
    #purchaseOrder.save

    #开始事务，确保在流水号正常的情况下，保存采购订单,一但出现问题，则循环执行
    begin
      Sequence.transaction do
        #开始为采购订单取得流水号
        sequence = Sequence.where("company_id = ? AND sub_type = ?", session[:company_id], PurchaseOrder.name).first

        sequence.seq_no = sequence.seq_no + 1
        purchaseOrder.seq_number = sequence.seq_no
        purchaseOrder.order_number = sequence.ab + ":" + purchaseOrder.seq_number.to_s + ":" + Date.today.to_s
        sequence.save!
        purchaseOrder.save!
      end
    rescue ActiveRecord::StaleObjectError
      #这个异常是说明，你当提交时，有人提前更新了你之前读取的信息，违反乐观锁。要retry
      #这里特别指序号产生表。
      logger.info "somebody using sn before yours.............................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip, "StaleObjectError")
      retry
    rescue ActiveRecord::RecordNotFound
      logger.info "RecordNotFound................................................................................"
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip, "RecordNotFound")
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip, e.to_s)
      logger.info e
    end

    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text => result, :layout => false
  end

  #编辑后的保存
  def update
    data = params[:data]
    begin
      paramsHash = Util.paramsPreprocessToHash(params[:data])

      #productHash = paramsHash["products"][0]
      role = Role.find(session[:role_id])
      if role.cross_company == "否"
        purchaseOrder = PurchaseOrder.where("id = ? AND company_id = ? AND is_locked <> 1 AND (auditing_status is null OR auditing_status <> ?)", paramsHash['id'], session[:company_id], '通过').first
      else
        purchaseOrder = PurchaseOrder.where("id = ? AND is_locked <> 1 AND (auditing_status is null OR auditing_status <> ?)", paramsHash['id'], '通过').first
      end
      if purchaseOrder != nil
        PurchaseOrder.transaction do
          #如果在保存时，有人编辑过，则不能保证
          if purchaseOrder.lock_version > paramsHash['lock_version'].to_i
            info="有其它用户在您保存之前编辑过此采购订单记录，请从新编辑！"
            result = "{success:true,info:'#{info}'}"
            render :text => result, :layout => false and return false
          end

          #purchaseOrder.company_id = paramsHash['company_id']
          purchaseOrder.department_id = session[:department_id]
          purchaseOrder.employee_id = session[:employee_id]
          purchaseOrder.vendor_id = paramsHash['vendor_id']
          purchaseOrder.linkman = paramsHash['linkman']
          purchaseOrder.phone = paramsHash['phone']
          purchaseOrder.delivery_address = paramsHash['delivery_address']
          purchaseOrder.contract_number = paramsHash['contract_number']
          purchaseOrder.tax_rate = paramsHash['tax_rate']
          purchaseOrder.action_date = paramsHash['action_date']
          purchaseOrder.description = paramsHash['description']

          purchaseOrder.audit_opinion = ''
          purchaseOrder.auditor_id = ''


          #判断是暂存还是提交,结合审批一起处理，如果是暂存，就不处理审批的情形
          if paramsHash['temporary'] == '1'
            purchaseOrder.deal_with_status = Constants::TEMP_ADD
          else
            #采购的修改，不需要审批。可以编辑后直接生效。
            purchaseOrder.auditing_status = Constants::PASS_APPLY_EDIT
            purchaseOrder.deal_with_status = ''
            #记录变更历史
            purchaseOrderHx = PurchaseOrderHx.new
            purchaseOrderHx.purchase_order_id = purchaseOrder.id
            purchaseOrderHx.company_id = session[:company_id]
            purchaseOrderHx.department_id = session[:department_id]
            purchaseOrderHx.employee_id = session[:employee_id]
            purchaseOrderHx.amount = purchaseOrder.amount
            purchaseOrderHx.tax_amount = purchaseOrder.tax_amount
            purchaseOrderHx.value_added_tax = purchaseOrder.value_added_tax
            purchaseOrderHx.vendor_id = purchaseOrder.vendor_id
            purchaseOrderHx.seq_number = purchaseOrder.seq_number
            purchaseOrderHx.order_number = purchaseOrder.order_number
            purchaseOrderHx.save!
          end

          #products信息
          productsHashArray = paramsHash["products"]
          #在这里，要作一个增，删，编辑操作，以前台数据为准。
          #首先各取出前台与后台的ID数组
          fgIdArray = Array.new
          productsHashArray.each do |productHash|
            #fgIdArray << productHash["id"].to_i
            #要用销售订单号+产品号，取代purchaseOrderDetailId
            fgIdArray << productHash["sale_order_id"] + "|" + productHash["product_id"]
          end

          bgIdArray = Array.new
          purchaseOrderDetails = purchaseOrder.purchase_order_details
          purchaseOrderDetails.each do |purchaseOrderDetail|
            #bgIdArray << purchaseOrderDetail.id
            #要用销售订单号+产品号，取代purchaseOrderDetailId
            bgIdArray << purchaseOrderDetail.sale_order_id.to_s + "|" + purchaseOrderDetail.product_id.to_s
            #记录历史变更
            if !purchaseOrderHx.nil?
              purchaseOrderHxDetail = PurchaseOrderHxDetail.new
              purchaseOrderHxDetail.purchase_order_hx_id = purchaseOrderHx.id
              purchaseOrderHxDetail.sale_order_id = purchaseOrderDetail.sale_order_id
              purchaseOrderHxDetail.product_id = purchaseOrderDetail.product_id
              purchaseOrderHxDetail.quantity = purchaseOrderDetail.quantity
              purchaseOrderHxDetail.unit_price = purchaseOrderDetail.unit_price
              purchaseOrderHxDetail.amount = purchaseOrderDetail.amount
              purchaseOrderHxDetail.tax_price = purchaseOrderDetail.tax_price
              purchaseOrderHxDetail.tax_amount = purchaseOrderDetail.tax_amount
              purchaseOrderHxDetail.value_added_tax = purchaseOrderDetail.value_added_tax
              purchaseOrderHxDetail.description = purchaseOrderDetail.description
              purchaseOrderHxDetail.save!
            end
          end

          idIntersectionArray = fgIdArray & bgIdArray
          addIdArray = fgIdArray - idIntersectionArray
          delIdArray = bgIdArray - idIntersectionArray
          logger.info "delIdArray............................................"
          logger.info delIdArray
          #如果不为空，再判断并删除
          if !delIdArray.empty?
            delIdArray.each do |item|
              saleOrderDelId = item.split(/\|/)[0]
              productDelId = item.split(/\|/)[1]
              PurchaseOrderDetail.delete_all("purchase_order_id = #{purchaseOrder.id} AND sale_order_id = #{saleOrderDelId.to_i} AND product_id = #{productDelId.to_i}")
            end
          end

          #在进行从新整理数据之前，先把采购订单的总金额置“0”
          purchaseOrder.amount = 0
          purchaseOrder.value_added_tax = 0
          purchaseOrder.tax_amount = 0
          productsHashArray.each do |productHash|
            purchaseOrderDetail = nil
            #只有当用户选择的产品不为空时，才有详细订单。
            if productHash["product_id"] !=""
              #没Id说明是新增加的。, 里要注意，不同的采购订单详细项会有相同的产品，也就是说同一个产品Id,并能决定一条记录的唯一性，还要结合sale_order_id
              if productHash["id"] == "" #此处的Id是指purchaseOrderDetail的Id
                                         #TODO:这里其实还有一种情况，在判断了这种情况以后，再修改，就是虽然没有purchasedetailid但是有product_id
                                         #这种情况是由于用户删除了产品，又添加了同一个产品引起的。这种情况下就要从新抓取出记录来继续修改而不是添加
                purchaseOrderDetail = PurchaseOrderDetail.first(:conditions => ["purchase_order_id = ? AND sale_order_id = ? AND product_id = ?", purchaseOrder.id, productHash["sale_order_id"].to_i, productHash["product_id"].to_i])
                if purchaseOrderDetail.nil?
                  purchaseOrderDetail = PurchaseOrderDetail.new
                  #这儿从新改造，根据sale_order_id从新得到saleOrderDetail再得到Id
                  purchaseOrderDetail.sale_order_id = productHash["sale_order_id"]
                  purchaseOrderDetail.product_id = productHash["product_id"]
                end
              else
                #这里要作一个特殊的处理，就是purchaseDetailId没有删，ProductID也没有变，但saleOrderId变了。这样if !delIdArray.empty?，这一句就会把
                #相关的purchaseDetailId给删了。这时就要判断了，如果有就改，如果没有，就要从新添加了
                #purchaseOrderDetail = PurchaseOrderDetail.find(productHash["id"].to_i)
                #purchaseOrderDetail.sale_order_id = productHash["sale_order_id"]
                #purchaseOrderDetail.product_id = productHash["product_id"]
                purchaseOrderDetailsFromDB = PurchaseOrderDetail.where("id=#{productHash["id"]}")
                if purchaseOrderDetailsFromDB.length == 0
                  purchaseOrderDetail = PurchaseOrderDetail.new
                  purchaseOrderDetail.purchase_order_id = purchaseOrder.id
                  purchaseOrderDetail.product_id = productHash["product_id"]
                else
                  purchaseOrderDetail = purchaseOrderDetailsFromDB[0]
                end
              end
              purchaseOrderDetail.quantity = productHash["quantity"]
              purchaseOrderDetail.unit_price = productHash["unit_price"]
              purchaseOrderDetail.tax_price = productHash["tax_price"]
              purchaseOrderDetail.tax_amount = productHash["tax_amount"]
              purchaseOrderDetail.value_added_tax = productHash["value_added_tax"]
              purchaseOrderDetail.amount = productHash["amount"]
              purchaseOrder.amount = purchaseOrder.amount + purchaseOrderDetail.amount #计算订单总金额
              purchaseOrder.tax_amount = purchaseOrder.tax_amount + purchaseOrderDetail.tax_amount #计算订单总金额(含税)
              purchaseOrder.value_added_tax = purchaseOrder.value_added_tax + purchaseOrderDetail.value_added_tax #总税
              purchaseOrderDetail.description = productHash["description"]
              purchaseOrder.purchase_order_details << purchaseOrderDetail
            end
          end

          #在这儿对比一下采购修改后，与入库发生的变化，以从新设置采购订单的入库状态。
          diffs = PurchaseOrder.diff_purchase_entry(purchaseOrder.id)
          #不等于0有二种情况，一是采购的多了入库的少了，二是入的多采购的少了。不管如何，入库状态都设置为""
          if diffs.length !=0
            purchaseOrder.store_status = Constants::ENTERING
          elsif diffs.length == 0
            purchaseOrder.store_status = Constants::FINISH_ENTRY
          end
          purchaseOrder.save!
        end
      end
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip, e.to_s)
    end
    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text => result, :layout => false
  end

  #得到可供入库的详细货品种类与数量，已经入过的会排除在外。这次要针对product_id分组，因为在采购订单中是由销售订单和产品二个参数分组的。
  #此版本的修改是为了显示每个采购订单中的不同的销售订单的单号。不再以产品Id为唯一区分。
  def getPurchaseOrderDetailBalanceForEntry
    purchaseOrderId = params[:purchase_order_id]
    purchaseOrders = PurchaseOrder.all(:select => "pd.id,so.order_number as sale_order_number,pd.sale_order_id as sale_order_id,p.id as product_id,p.name as product_name,p.is_suit,p.unit_price,p.number,p.spec,p.unit,sum(pd.quantity) as quantity,sum(pd.amount) as amount,pd.description,newed.quantity as ed_quantity,(sum(pd.quantity) - ifnull(newed.quantity,0)) as balance_quantity", :joins => "po
left join purchase_order_details pd on po.id = pd.purchase_order_id
left join (select warehousing_entry_id,ed.sale_order_id,e.purchase_order_id,product_id,sum(quantity) as quantity
from warehousing_entries e left join warehousing_entry_details ed on e.id = ed.warehousing_entry_id
where e.purchase_order_id = "+purchaseOrderId+" AND e.auditing_status != '#{Constants::PASS_APPLY_CANCEL}'
group by product_id,ed.sale_order_id) newed on newed.product_id = pd.product_id AND newed.sale_order_id = pd.sale_order_id
left join products p on p.id = pd.product_id
left join sale_orders so on so.id = pd.sale_order_id
left join sale_order_details sd on pd.sale_order_id = sd.sale_order_id AND pd.product_id = sd.product_id
where po.id =  "+purchaseOrderId+ " group by pd.product_id,pd.sale_order_id,sd.id having sum(pd.quantity) - ifnull(newed.quantity,0) > 0")

    jsonStr="{totalProperty:"+purchaseOrders.length.to_s+",root:"+purchaseOrders.to_json()+"}"
    #logger.info jsonStr
    render :text => jsonStr, :layout => false
  end

  #得到某采购订单的详细信息，并显示与入库订单之间的数量差比
  def getPurchaseOrderDetailsBalanceById
    purchaseOrderId = params[:purchase_order_id]
    #在这儿要判断一下，只有具有财务权限的用户才可以看到成本等价格
    if session[:financial_management] == '是'
      selectStr = "pd.id,so.order_number as sale_order_number,so.auditing_status as sale_order_status,p.name as product_name,p.number as product_number,p.is_suit,pd.unit_price,p.number,p.spec,p.unit,pd.quantity,pd.amount,pd.tax_amount,pd.tax_price,pd.value_added_tax,pd.description,newed.quantity as ed_quantity,(ifnull(newed.quantity,0)-pd.quantity) as balance_quantity"
    else
      selectStr = "pd.id,so.order_number as sale_order_number,so.auditing_status as sale_order_status,p.name as product_name,p.number as product_number,p.is_suit,p.number,p.spec,p.unit,pd.quantity,pd.description,newed.quantity as ed_quantity,(ifnull(newed.quantity,0)-pd.quantity) as balance_quantity"
    end
    purchaseOrders = PurchaseOrder.select("#{selectStr}").joins("po left join purchase_order_details pd on po.id = pd.purchase_order_id
left join (select warehousing_entry_id,e.purchase_order_id,ed.sale_order_id,product_id,sum(quantity) as quantity
from warehousing_entries e left join warehousing_entry_details ed on e.id = ed.warehousing_entry_id
where e.purchase_order_id = "+purchaseOrderId+" AND e.auditing_status != '#{Constants::PASS_APPLY_CANCEL}'
group by product_id,ed.sale_order_id) newed on newed.product_id = pd.product_id AND newed.sale_order_id = pd.sale_order_id
left join products p on p.id = pd.product_id
left join sale_orders so on so.id = pd.sale_order_id
where po.id =  "+purchaseOrderId)
    if session[:financial_management] == "是"
      jsonStr="{totalProperty:"+purchaseOrders.length.to_s+",root:"+purchaseOrders.to_json()+"}"
    else
      jsonStr="{totalProperty:"+purchaseOrders.length.to_s+",root:"+purchaseOrders.to_json(:except => [:amount, :tax_price, :tax_amount, :value_added_tax])+"}"
    end

    #logger.info jsonStr
    render :text => jsonStr, :layout => false
  end

  #申请撤消采购订单,如果采购订单没有被初级审批过，则可以直接设置为撤消液态。
  def applyToCancel
    purchaseOrder = PurchaseOrder.find(params[:id])
    if (purchaseOrder.auditing_status.include? "通过") || (purchaseOrder.auditing_status.include? "驳回")
      purchaseOrder.auditing_status = Constants::AUDIT_APPLY_CANCEL
      purchaseOrder.deal_with_status = Constants::AUDIT_APPLY_CANCEL
    else
      #申请状态，可以直接标记为撤消
      purchaseOrder.auditing_status = Constants::PASS_APPLY_CANCEL
      purchaseOrder.deal_with_status = Constants::CANCELED
      #通过状态，要经过审批
    end
    purchaseOrder.auditor_id = session[:employee_id]
    purchaseOrder.save!

    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text => result, :layout => false
  end

  #根据审批的结果，处理采购订单，如果审批同意，则取消所有入库订单。

  def updateAuditingCancelStatus
    purchaseOrder = PurchaseOrder.find(params[:purchase_order_id])
    if params[:auditing_status]=='是'
      purchaseOrder.auditing_status = Constants::PASS_APPLY_CANCEL
      purchaseOrder.deal_with_status = Constants::CANCELED
      purchaseOrder.audit_opinion = params[:audit_opinion]
    else
      purchaseOrder.audit_opinion = params[:audit_opinion]
      purchaseOrder.auditing_status = Constants::REJECT_APPLY_CANCEL
    end
    purchaseOrder.auditor_id = session[:employee_id]
    purchaseOrder.save!
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text => result, :layout => false
  end

  #将销售订单转换为采购订单
  def transformSaleIntoPurchase
    paramsHash = Util.paramsPreprocessToHash(params[:data])
    #productHash = paramsHash["products"][0]

    purchaseOrder = PurchaseOrder.new
    purchaseOrder.company_id = session[:company_id]
    purchaseOrder.department_id = session[:department_id]
    purchaseOrder.employee_id = session[:employee_id]
    purchaseOrder.vendor_id = paramsHash['vendor_id']
    purchaseOrder.linkman = paramsHash['linkman']
    purchaseOrder.phone = paramsHash['phone']
    purchaseOrder.delivery_address = paramsHash['delivery_address']
    purchaseOrder.contract_number = paramsHash['contract_number']
    purchaseOrder.tax_rate = paramsHash['tax_rate']
    purchaseOrder.action_date = paramsHash['action_date']
    purchaseOrder.description = paramsHash['description']
    purchaseOrder.sale_order_id = paramsHash['sale_order_id']

    #判断一下当前用户角色是否需求审批
    sysParam = SysParam.find_by_company_id(session[:company_id])

    #判断是暂存还是提交,结合审批一起处理，如果是暂存，就不处理审批的情形
    if paramsHash['temporary'] == '1'
      purchaseOrder.deal_with_status = Constants::TEMP_ADD
    else
      if sysParam.audit_for_purchase_add == "否"
        purchaseOrder.auditing_status = Constants::PASS_APPLY_ADD
        purchaseOrder.deal_with_status = ''
      else
        purchaseOrder.auditing_status = Constants::AUDIT_APPLY_ADD
      end
    end

    #插入products信息
    productsHashArray = paramsHash["products"]
    productsHashArray.each do |productHash|
      #只有当用户选择的产品不为空时，才有详细订单。
      if productHash["product_id"] !=""
        purchaseOrderDetail = PurchaseOrderDetail.new
        purchaseOrderDetail.product_id = productHash["product_id"]
        purchaseOrderDetail.quantity = productHash["quantity"]
        purchaseOrderDetail.unit_price = productHash["unit_price"]
        #purchaseOrderDetail.discount = productHash["discount"]
        purchaseOrderDetail.amount = productHash["amount"]
        purchaseOrder.amount = purchaseOrder.amount + purchaseOrderDetail.amount #计算订单总金额
        purchaseOrderDetail.description = productHash["description"]
        purchaseOrder.purchase_order_details << purchaseOrderDetail
      end
    end
    #purchaseOrder.save

    #开始事务，确保在流水号正常的情况下，保存采购订单,一但出现问题，则循环执行
    begin
      Sequence.transaction do
        #开始为采购订单取得流水号
        sequence = Sequence.where("company_id = ? AND sub_type = ?", session[:company_id], PurchaseOrder.name).first

        sequence.seq_no = sequence.seq_no + 1
        purchaseOrder.seq_number = sequence.seq_no
        purchaseOrder.order_number = sequence.ab + ":" + purchaseOrder.seq_number.to_s + ":" + Date.today.to_s
        sequence.save!
        purchaseOrder.save!
        #把销售订单的状态转为“已转采购”
        saleOrder = SaleOrder.find(paramsHash['sale_order_id'])
        saleOrder.is_transformed_into_purchase = '是'
        saleOrder.save!
      end
    rescue ActiveRecord::StaleObjectError
      #这个异常是说明，你当提交时，有人提前更新了你之前读取的信息，违反乐观锁。要retry
      #这里特别指序号产生表。
      logger.info "somebody using sn before yours.............................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip, "StaleObjectError")
      retry
    rescue ActiveRecord::RecordNotFound
      logger.info "RecordNotFound................................................................................"
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip, "RecordNotFound")
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip, e.to_s)
      logger.info e
    end

    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text => result, :layout => false
  end

  #得到某个采购订单的所有付款
  def getPayablesByPurchaseId
    payables = Payable.where("purchase_order_id = ?", params[:id]).includes(:employee)
    jsonStr = "{totalProperty:"+payables.length.to_s+",root:"+payables.to_json(:include => [:employee])+"}"
    render :text => jsonStr, :layout => false
  end

  #得到销售订单中，还没有进行采购的产品信息。
  def getProductNeedPurchase
    #begin
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i
    conditionsStr = ''

    if params[:sale_order_number].to_s != ''
      conditionsStr = conditionsStr + "s.seq_number in (#{params[:sale_order_number]})"
    end

    if params[:auditing_status].to_s != '' && params[:auditing_status] != ' '
      if conditionsStr == ''
        conditionsStr = "auditing_status like '%#{params[:auditing_status].to_s}%'"
      else
        conditionsStr = conditionsStr+" AND auditing_status like '%#{params[:auditing_status].to_s}%'"
      end
    end

    if params[:begin_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = "s.action_date >= '#{params[:begin_date]}'"
      else
        conditionsStr = conditionsStr+" AND s.action_date >= '#{params[:begin_date]}'"
      end
    end

    if params[:end_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = "s.action_date <= '#{params[:end_date]}'"
      else
        conditionsStr = conditionsStr+" AND s.action_date <= '#{params[:end_date]}'"
      end
    end

    if params[:vendor_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = "v.id = #{params[:vendor_id]}"
      else
        conditionsStr = conditionsStr+" AND v.id = #{params[:vendor_id]}"
      end
    end

    if conditionsStr != ""
      conditionsStr = "where " + conditionsStr
    end
    logger.info "purchase_info"
    logger.info params[:purchase_info]
    logger.info params[:purchase_info] == "true"
    if params[:purchase_info] == "true"
      saleOrders = SaleOrder.all(:select => "s.id as sale_id,s.auditing_status as sale_auditing_status,pd.auditing_status as purchase_auditing_status,s.order_number as sale_order_number,s.action_date,sd.quantity as sale_quantity,p.name as product_name,p.number as product_number,pd.order_number as purchase_order_number,pd.quantity as purchase_quantity ,d.name as department_name,pd.store_status,v.name as vendor_name,ifnull(pc1.stock_quantity,0) as stock_quantity_1,ifnull(pc2.stock_quantity,0) as stock_quantity_2", :joins => "s
left join sale_order_details sd on s.id = sd.sale_order_id  AND sd.is_locked = 0
left join (select pd.sale_order_id,pd.product_id,pd.quantity,po.order_number,po.store_status,po.vendor_id,po.auditing_status from purchase_orders po
           left join purchase_order_details pd on po.id = pd.purchase_order_id where po.auditing_status !='#{Constants::PASS_APPLY_CANCEL}' ) pd
          on sd.sale_order_id = pd.sale_order_id AND sd.product_id = pd.product_id
left join products p on p.id = sd.product_id
left join departments d on d.id = s.department_id
left join vendors v on v.id = pd.vendor_id
left join (select product_id,sum(quantity) as stock_quantity from product_collections where is_locked = 0 AND warehouse_id = 1 group by product_id) pc1 on pc1.product_id = p.id
left join (select product_id,sum(quantity) as stock_quantity from product_collections where is_locked = 0 AND warehouse_id = 2 group by product_id) pc2 on pc2.product_id = p.id
#{conditionsStr}")
    else
      saleOrders = SaleOrder.all(:select => "s.id as sale_id,s.auditing_status as sale_auditing_status,pd.auditing_status as purchase_auditing_status,s.order_number as sale_order_number,s.action_date ,sd.quantity as sale_quantity,p.name as product_name,p.number as product_number,sum(pd.quantity) as purchase_quantity ,d.name as department_name,v.name as vendor_name,ifnull(pc1.stock_quantity,0) as stock_quantity_1,ifnull(pc2.stock_quantity,0) as stock_quantity_2", :joins => "s
left join sale_order_details sd on s.id = sd.sale_order_id  AND sd.is_locked = 0
left join (select pd.sale_order_id,pd.product_id,pd.quantity,po.order_number,po.store_status,po.vendor_id,po.auditing_status from purchase_orders po
           left join purchase_order_details pd on po.id = pd.purchase_order_id where po.auditing_status !='#{Constants::PASS_APPLY_CANCEL}') pd
          on sd.sale_order_id = pd.sale_order_id AND sd.product_id = pd.product_id
left join products p on p.id = sd.product_id
left join departments d on d.id = s.department_id
left join vendors v on v.id = pd.vendor_id
left join (select product_id,sum(quantity) as stock_quantity from product_collections where is_locked = 0 AND warehouse_id = 1 group by product_id) pc1 on pc1.product_id = p.id
left join (select product_id,sum(quantity) as stock_quantity from product_collections where is_locked = 0 AND warehouse_id = 2 group by product_id) pc2 on pc2.product_id = p.id
#{conditionsStr} group by s.id,p.id")
    end
    jsonStr = saleOrders.to_json

    jsonStr="{totalProperty:"+saleOrders.length.to_s+",root:"+saleOrders.to_json()+"}"
    #logger.info jsonStr
    render :text => jsonStr, :layout => false
    #    rescue Exception => e
    #      logger.info e
    #      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    #    end
  end

  #得到采购订单中，还没有进行入库的产品信息。
  def getProductNeedEntry
    #begin
    paramsHash = Hash.new
    paramsHash[:offset] = params[:start].to_i
    paramsHash[:limit] = params[:limit].to_i
    conditionsStr = ''

    if params[:purchase_order_number].to_s != ''
      conditionsStr = conditionsStr + "po.seq_number in (#{params[:purchase_order_number]})"
    end

    if params[:auditing_status].to_s != '' && params[:auditing_status] != ' '
      if conditionsStr == ''
        conditionsStr = "auditing_status like '%#{params[:auditing_status]}%'"
      else
        conditionsStr = conditionsStr+ " AND auditing_status like '%#{params[:auditing_status]}%'"
      end
    end

    if params[:begin_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = "po.action_date >= '#{params[:begin_date]}'"
      else
        conditionsStr = conditionsStr+" AND po.action_date >= '#{params[:begin_date]}'"
      end
    end

    if params[:end_date].to_s != ''
      if conditionsStr == ''
        conditionsStr = "po.action_date <= '#{params[:end_date]}'"
      else
        conditionsStr = conditionsStr+" AND po.action_date <= '#{params[:end_date]}'"
      end
    end

    if params[:vendor_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = "v.id = #{params[:vendor_id]}"
      else
        conditionsStr = conditionsStr+" AND v.id = #{params[:vendor_id]}"
      end
    end

    if params[:product_id].to_s != ''
      if conditionsStr == ''
        conditionsStr = "pd.product_id = #{params[:product_id]}"
      else
        conditionsStr = conditionsStr+" AND pd.product_id = #{params[:product_id]}"
      end
    end

    if conditionsStr != ""
      conditionsStr = "where " + conditionsStr
    end

    if params[:entry_info] == "true"
      #要对where再处理一下。以不显示数量为0即没有进货的入库详细表信息
      #      if conditionsStr != ""
      #        conditionsStr = conditionsStr + "AND ed.quantity is not null"
      #      else
      #        conditionsStr = "where ed.quantity is not null"
      #      end
      purchaseOrders = PurchaseOrder.all(:select => "po.id as purchase_order_id,po.auditing_status,po.order_number as purchase_order_number,ed.order_number as entry_order_number,po.action_date ,po.auditing_status ,pd.quantity as purchase_quantity,p.name as product_name,p.number as product_number,ifnull(ed.quantity,0) as entry_quantity ,d.name as department_name,po.store_status,v.name as vendor_name", :joins => "po
left join purchase_order_details pd on po.id = pd.purchase_order_id AND pd.is_locked = 0
left join (select we.order_number,ed.purchase_order_id,ed.sale_order_id,ed.product_id,sum(ed.quantity) quantity from warehousing_entries we
           left join warehousing_entry_details ed on we.id = ed.warehousing_entry_id where we.auditing_status != '#{Constants::PASS_APPLY_CANCEL}' group by ed.id) ed
           on pd.sale_order_id = ed.sale_order_id AND pd.product_id = ed.product_id AND pd.purchase_order_id = ed.purchase_order_id
left join products p on p.id = pd.product_id
left join departments d on d.id = po.department_id
left join vendors v on v.id = po.vendor_id
#{conditionsStr}")
    else
      purchaseOrders = PurchaseOrder.all(:select => "po.id as purchase_order_id,po.auditing_status,po.order_number as purchase_order_number,po.action_date ,po.auditing_status ,pd.quantity as purchase_quantity,p.name as product_name,p.number as product_number,ifnull(ed.quantity,0) as entry_quantity ,d.name as department_name,po.store_status,v.name as vendor_name", :joins => "po
left join purchase_order_details pd on po.id = pd.purchase_order_id AND pd.is_locked = 0
left join (select ed.purchase_order_id,ed.sale_order_id,ed.product_id,sum(ed.quantity) quantity from warehousing_entries we
           left join warehousing_entry_details ed on we.id = ed.warehousing_entry_id where we.auditing_status != '#{Constants::PASS_APPLY_CANCEL}' group by ed.sale_order_id,ed.purchase_order_id,ed.product_id) ed
           on pd.sale_order_id = ed.sale_order_id AND pd.product_id = ed.product_id AND pd.purchase_order_id = ed.purchase_order_id
left join products p on p.id = pd.product_id
left join departments d on d.id = po.department_id
left join vendors v on v.id = po.vendor_id
#{conditionsStr} group by pd.id,p.id")
    end
    jsonStr = purchaseOrders.to_json

    jsonStr="{totalProperty:"+purchaseOrders.length.to_s+",root:"+purchaseOrders.to_json()+"}"
    #logger.info jsonStr
    render :text => jsonStr, :layout => false
  end

  #针对某销售订单得到采购时最大可以采购的产品数量
  def getProductQuantityForPurchase
    saleOrderId = params[:sale_order_id]
    productId = params[:product_id]
    purchasedProductQuantity = PurchaseOrder.first(:select => "sum(pd.quantity) as quantity", :joins => " p left join purchase_order_details pd on p.id = pd.purchase_order_id where (p.auditing_status = '#{Constants::PASS_APPLY_ADD}' OR p.auditing_status = '#{Constants::PASS_APPLY_EDIT }') AND pd.sale_order_id = #{saleOrderId} AND pd.product_id = #{productId}")
    saleQuantity = SaleOrderDetail.first(:select => "sum(quantity) as quantity", :conditions => ["sale_order_id = ? AND product_id = ?", saleOrderId, productId])
    quantity = saleQuantity.quantity.to_i - purchasedProductQuantity.quantity.to_i
    logger.info quantity
    render :text => quantity, :layout => false
  end

  #得到采购订单中某产品的入库数量
  def getEntryProductQuantityForPurchase
    purchaseOrderId = params[:purchase_order_id]
    saleOrderId = params[:sale_order_id]
    productId = params[:product_id]
    warehousingEntry = WarehousingEntry.first(:select => "sum(ed.quantity) as quantity", :joins => " we left join warehousing_entry_details ed on we.id = ed.warehousing_entry_id where we.auditing_status != '#{Constants::PASS_APPLY_CANCEL}' AND ed.sale_order_id = #{saleOrderId} AND ed.product_id = #{productId}")
    logger.info warehousingEntry.quantity
    render :text => warehousingEntry.quantity, :layout => false
  end

  #得到某个采购订单下的所有销售订单信息。
  #在编辑入库订单时需要，因为一个入库订单，只能对应一个采购编号
  #!暂时无用。准备删除
  def getSaleOrdersOfPurchaseById
    purchaseOrderDetails = PurchaseOrderDetail.where("purchase_order_id = ?", params[:id]).group(:sale_order_id).includes([:sale_order])
    jsonStr = "{totalProperty:"+purchaseOrderDetails.length.to_s+",root:"+purchaseOrderDetails.to_json(:include => {:sale_order => {:only => :order_number}})+"}"
    render :text => jsonStr, :layout => false
  end

  #得到变更历史的摘要
  def getHxesByPurchaseId
    purchaseOrderHxes = PurchaseOrderHx.where(purchase_order_id:params[:id]).includes([:department, :employee])
    jsonStr="{totalProperty:"+purchaseOrderHxes.length.to_s+",root:"+purchaseOrderHxes.to_json(:include => [:department, :employee])+"}"
    #logger.info jsonStr
    render :text => jsonStr, :layout => false
  end

  #根据变更Id得到详细信息
  def getHxDetailsByHxId
    purchaseOrderHxDetails = PurchaseOrderHxDetail.where(purchase_order_hx_id:params[:id]).includes([:product])
    jsonStr="{totalProperty:"+purchaseOrderHxDetails.length.to_s+",root:"+purchaseOrderHxDetails.to_json(:include => {:product => {:only => [:id, :name, :is_suit, :spec, :number]}})+"}"
    #logger.info jsonStr
    render :text => jsonStr, :layout => false
  end

  #采购额分析
  def getPurchasesForReport
    begin
      #begin
      conditionsStr = ''
      if params[:employee_id].to_s != ''
        conditionsStr = conditionsStr + " po.employee_id = #{params[:employee_id]}"
      end

      #处于申请或已撤消状态的订单，不计算在内。
      if conditionsStr == ''
        conditionsStr = " po.auditing_status not like '%#{Constants::APPLY}%' AND po.auditing_status not like '%#{Constants::PASS_APPLY_CANCEL}%' "
      else
        conditionsStr = conditionsStr + " AND po.auditing_status not like '%#{Constants::APPLY}%' AND po.auditing_status not like '%#{Constants::PASS_APPLY_CANCEL}%' "
      end

      if params[:begin_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = " po.created_at >= '#{params[:begin_date] + ' 00:00:00'}'"
        else
          conditionsStr = conditionsStr+" AND po.created_at >= '#{params[:begin_date] + ' 00:00:00'}'"
        end
      end

      if params[:end_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = " po.created_at <= '#{params[:end_date] + ' 59:59:59'}'"
        else
          conditionsStr = conditionsStr+" AND po.created_at <= '#{params[:end_date] + ' 59:59:59'}'"
        end
      end

      if params[:product_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = " pd.product_id = #{params[:product_id]}"
        else
          conditionsStr = conditionsStr+" AND pd.product_id = #{params[:product_id]} "
        end
      end

      if conditionsStr != ""
        conditionsStr = " where " + conditionsStr
      end

      #判断一下，如果是采购员分组，则显示采购员姓名，否则不显示。
      if params[:employee_group] == "true"
        selectStr = "sum(pd.amount) as amount,sum(pd.value_added_tax) as value_added_tax,sum(pd.tax_amount) as tax_amount,e.name as employee_name"
      else
        selectStr = "sum(pd.amount) as amount,sum(pd.value_added_tax) as value_added_tax,sum(pd.tax_amount) as tax_amount"
      end

      groupByStr = ""
      if params[:time_slot] == 'day'
        selectStr = selectStr + " ,DATE_FORMAT(po.created_at,'%Y-%m-%d') as time_slot"
        groupByStr = "group by time_slot"
      elsif params[:time_slot] == 'month'
        selectStr = selectStr + " ,DATE_FORMAT(po.created_at,'%Y-%m') as time_slot"
        groupByStr = "group by time_slot"
      elsif params[:time_slot] == 'year'
        selectStr = selectStr + " ,DATE_FORMAT(po.created_at,'%Y') as time_slot"
        groupByStr = "group by time_slot,"
      end

      #判断是否采购员分组
      if params[:employee_group] == "true"
        if groupByStr == ""
          groupByStr = "group by po.employee_id"
        else
          groupByStr += ",po.employee_id"
        end
      end

      if groupByStr != ""
        groupByStr += " order by amount DESC"
      end

      if params[:employee_id] == ''
        purchaseOrders = PurchaseOrder.all(:select => selectStr, :joins => "po left join purchase_order_details pd on pd.purchase_order_id = po.id
                                                                     left join products p on p.id = pd.product_id
                                                                     left join employees e on e.id = po.employee_id " + conditionsStr + groupByStr)
      else
        purchaseOrders = PurchaseOrder.all(:select => selectStr, :joins => "po left join purchase_order_details pd on pd.purchase_order_id = po.id
                                                                     left join products p on p.id = pd.product_id
                                                                     left join employees e on e.id = po.employee_id " + conditionsStr)
      end

      jsonStr="{totalProperty:"+purchaseOrders.length.to_s+",root:"+purchaseOrders.to_json(:include => [:department])+"}"
      #logger.info jsonStr
      render :text => jsonStr, :layout => false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip, e.to_s)
    end
  end

  #得到当前的所有产品，超出预警的值。
  def getProductStockRemindForReport
    products = Product.find_by_sql("select name,number,min_quantity,max_quantity,pc.quantity from products p
left join (
select sum(quantity) as quantity ,product_id
from product_collections where is_locked = 0
group by product_id ) pc on pc.product_id = p.id
where ( pc.quantity > p.max_quantity and p.max_quantity <> 0 ) OR ( pc.quantity < p.min_quantity and p.min_quantity <> 0 )")
    jsonStr="{totalProperty:"+products.length.to_s+",root:"+products.to_json()+"}"
    #logger.info jsonStr
    render :text => jsonStr, :layout => false
  end

  #生成打印销售凭证的头部
  def purchase_order_print_header
    @purchaseOrder = PurchaseOrder.find(params[:id], :include => [:department, :employee, :vendor])

  end

  #生成打印销售凭证的内容
  def purchase_order_print_content
    @purchaseOrder = PurchaseOrder.find(params[:id], :include => [:purchase_order_details, :employee, :vendor])
    @purchaseOrderDetails = @purchaseOrder.purchase_order_details
    @totalQuantity = @purchaseOrderDetails.sum(:quantity)
    logger.info @totalQuantity
  end

  def purchase_order_print_footer
    @purchaseOrder = PurchaseOrder.find(params[:id], :include => [:purchase_order_details, :employee, :vendor])
  end
end
